#!/bin/bash

if [ ! -d "/tmp/result_image" ]; then
    echo "Build failed! No results folder found."
    exit 1
fi

# copy result to ouput folder
sudo chown -R ebcl:ebcl /tmp/result_image
cp -R /tmp/result_image/* /build/results/images

BUILD_RESULT=$(find /tmp/result_image/* -maxdepth 0 -type d | head -n 1)
if [ -z "$BUILD_RESULT" ]; then
    echo "ERROR: No build result found!"
    exit 1
fi

BUILD_RESULT=$(basename $BUILD_RESULT)
BUILD_LOG="/tmp/result_image/${BUILD_RESULT}/result.log"

if [ -f $BUILD_LOG ]; then
        cat $BUILD_LOG | grep "\[[ ]*ERROR[ ]*\]:"
        if [ $? -eq 0 ]; then 
            echo "ERROR: Build failed, see result.log!"
            exit 1
        else
            echo "SUCCESS: Build was successful!"
            exit 0
        fi
else
        echo "ERROR: No build log found!"
        exit 1
fi

rm -rf /tmp/result_image
